package com.boot.es.es;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.es.entity.Phone;
import com.boot.es.lang.Renum;
import com.boot.es.service.PhoneService;
import com.boot.es.utils.RedisUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @date 2020/10/27 10:07
 */
@Component
public class PhoneES {

    @Autowired
    private PhoneService phoneService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    /**
     * 将数据库中的数据放到es中
     * @param keywords
     * @return
     * @throws IOException
     */
    public boolean parseContent(String keywords) throws IOException {
        List<Phone> contents = new ArrayList<>();
//        判断redis中有没有值，如果有直接去redis查询
        if (redisUtil.hasKey("phoneList")){
            String tagList = (String) redisUtil.get("tagList");
            contents = JSONObject.parseArray(tagList,Phone.class);
        }else {
//            没有去MySQL中查询，然后再存到redis中。
            contents = phoneService.list();
            String str = JSON.toJSON(contents).toString();
            redisUtil.set("tagList",str);
        }

        //把查询的数据放入ES中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i <contents.size() ; i++) {
            bulkRequest.add(new IndexRequest(keywords)
                    .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }


    /**
     * 查询
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws IOException
     */
    public List<Map<String ,Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
//        指定要查询的索引
        SearchRequest searchRequest = new SearchRequest("phone_info");

//        设置分页条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        pageNo = pageNo == 0 ? 1 : pageNo;
        pageSize = pageSize == 0 ? 10 : pageSize;
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

//        输入的关键字匹配的字段
        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title","*"+keyword+"*" );
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

//        执行
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        ArrayList<Map<String,Object>> list = new ArrayList<>();

        if (search.getHits().getHits().length!=0){
            for (SearchHit documentFields : search.getHits().getHits()) {
                list.add(documentFields.getSourceAsMap());
            }
            return list;
        }else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("code",404);
            map.put("msg","没有相关数据");
            list.add(map);
            return list;
        }
    }
}
